<template>
  <!-- 续费管理 -->
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="108px"
    >
      <el-form-item
        label="负责人"
        prop="userId"
        v-if="$auth.hasRoleOr(['admin', 'sdl'])"
      >
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择负责人"
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商机名称" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入商机订单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          placeholder="请选择客户名称"
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.customerId"
            :label="customer.customerName"
            :value="customer.customerId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称" prop="productId">
        <el-select
          v-model="queryParams.productId"
          placeholder="请选择产品类型"
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="product in productList"
            :key="product.productId"
            :label="product.productName"
            :value="product.productId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目进度" prop="progess">
        <el-select
          v-model="queryParams.progess"
          placeholder="请选择项目进度"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="dict in dict.type.project_progress"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="region">
        <el-cascader
          v-model="queryParams.region"
          :options="cityTree"
          :props="cascaderProps"
          style="width: 100%"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="下单时间" prop="queryTime">
        <el-date-picker
          clearable
          v-model="queryParams.queryTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-dd"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:order:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:order:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-c-scale-to-original"
          size="mini"
          @click="toApplyPage()"
          >产品折扣申请</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="负责人" align="center" prop="createBy" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="商机名称" align="center" prop="orderName" />
      <el-table-column label="订单金额" align="center" prop="amount" />
      <el-table-column label="项目归属" align="center" prop="orderAscription">
        <template slot-scope="scope">
          {{ coverGroupData(scope.row.orderAscription) }}
        </template>
      </el-table-column>
      <el-table-column
        label="项目进度"
        align="center"
        prop="progess"
        width="140"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.project_progress"
            :value="scope.row.progess"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="下次跟进时间"
        align="center"
        prop="nextFollowupTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.nextFollowupTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="是否续费"
        align="center"
        prop="progess"
        width="140"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.crm_order_renewal"
            :value="scope.row.isRenewal"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="续费时间"
        align="center"
        prop="renewalTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.renewalTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="续费金额" align="center" prop="renewalAmount" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:order:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="setRenewal(scope.row)"
            v-hasPermi="['crm:order:edit']"
            style="color: red"
            v-show="
              (scope.row.progess === '5' ||
                scope.row.progess === '6' ||
                scope.row.progess === '7') &&
              scope.row.isRenewal === '0'
            "
            >无续费</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:order:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商机对话框 -->
    <el-drawer
      ref="drawer"
      :title="title"
      direction="rtl"
      :visible.sync="open"
      size="80%"
      append-to-body
      :wrapperClosable="false"
      @close="handleClose"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
        type="border-card"
        style="margin: 0 20px; min-height: 90vh"
        v-if="!addFlag"
      >
        <el-tab-pane label="项目信息" name="addOrUpdateOrder">
          <addOrUpdateOrder
            lazy
            ref="addOrUpdateOrder"
            :userList="userList"
            :customerList="customerList"
            :productList="productList"
            :orderId="orderId"
            @cancel="cancel"
            isRenewal="1"
          ></addOrUpdateOrder>
        </el-tab-pane>
        <el-tab-pane label="拜访记录" name="second">
          <orderTrace
            lazy
            ref="orderTrace"
            :orderId="orderId"
            @cancel="cancel"
          ></orderTrace>
        </el-tab-pane>
        <el-tab-pane label="项目立项表" name="orderRegister" lazy>
          <orderRegister
            ref="orderRegister"
            :userList="userList"
            :customerList="customerList"
            :orderInfo="form"
            @cancel="cancel"
          ></orderRegister>
        </el-tab-pane>
        <el-tab-pane label="项目结算表" name="orderClear">
          <orderClear
            ref="orderClear"
            :userList="userList"
            :customerList="customerList"
            :orderInfo="form"
            @cancel="cancel"
          ></orderClear>
        </el-tab-pane>
      </el-tabs>
      <el-card
        v-else
        ref="card"
        class="box-card"
        style="width: 96%; margin: 0 20px; min-height: 90vh"
      >
        <addOrUpdateOrder
          ref="addOrUpdateOrder"
          :userList="userList"
          :customerList="customerList"
          :productList="productList"
          isRenewal="1"
          @cancel="cancel"
          :orderId="orderId"
        ></addOrUpdateOrder>
      </el-card>
    </el-drawer>
  </div>
</template>

<script>
import addOrUpdateOrder from "@/views/crm/order/components/pc/components/addOrUpdateOrder.vue";
import orderRegister from "@/views/crm/order/orderRegister/pc/index.vue";
import orderTrace from "@/views/crm/order/components/pc/components/orderTrace.vue";
import orderClear from "../../../orderClear/pc/index.vue";
import { listOrder, delOrder, setRenewal } from "@/api/crm/order";

export default {
  name: "Order",
  dicts: ["project_type", "project_progress", "crm_order_renewal"],
  components: {
    addOrUpdateOrder,
    orderTrace,
    orderRegister,
    orderClear,
  },
  props: {
    userList: {
      type: Array,
      default: [],
    },
    customerList: {
      type: Array,
      default: [],
    },
    productList: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      orderId: "",
      addFlag: true,
      activeName: "addOrUpdateOrder",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商机表格数据
      orderList: [],
      parentOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderName: null,
        customerId: null,
        amount: null,
        helpPerson: null,
        contactContent: null,
        type: null,
        budget: null,
        progess: null,
        contactPerson: null,
        clientPhone: null,
        cooperater: null,
        cooperaterPerson: null,
        cooperaterPhone: null,
        plan: null,
        nextFollowupTime: null,
        planPurchaseTime: null,
        status: null,
        planAmount: null,
        renewalTime: null,
        renewalAmount: null,
        userId: this.$store.getters.userId,
        queryTime: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderName: [
          { required: true, message: "订单名称不能为空", trigger: "blur" },
        ],
        customerId: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        amount: [
          { required: true, message: "订单金额不能为空", trigger: "blur" },
        ],
        contactContent: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        productId: [{ required: true, message: "不能为空", trigger: "blur" }],
        budget: [{ required: true, message: "不能为空", trigger: "blur" }],
        progess: [{ required: true, message: "不能为空", trigger: "blur" }],
        planPurchaseTime: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        planAmount: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    setRenewal(row) {
      row.isRenewal = "2";
      setRenewal(row).then((res) => {
        this.$modal.msgSuccess("删除成功");
      });
    },
    toApplyPage() {
      this.$router.replace("/crm/discount");
    },
    handleClose(done) {
      this.activeName = "addOrUpdateOrder";
    },
    handleClick(tab, event) {
      this.$nextTick(() => {
        this.form = this.$refs.addOrUpdateOrder.form;
        this.$refs[this.activeName].getData();
      });
    },
    /** 查询商机列表 */
    getList() {
      this.loading = true;
      this.queryParams.orderType = "1";
      listOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addFlag = true;
      this.open = true;
      this.title = "添加商机";
      this.orderId = "_" + new Date().getTime();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.addFlag = false;
      this.open = true;
      this.title = "修改商机";
      this.orderId = row.orderId + "_" + new Date().getTime();
      this.$nextTick(() => {
        this.$refs[this.activeName].reset();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal
        .confirm('是否确认删除商机编号为"' + orderIds + '"的数据项？')
        .then(function () {
          return delOrder(orderIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/order/export",
        {
          ...this.queryParams,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding: 0 20px;
}
</style>